/*
 * 图像上传控件
 * 
 * id：注入头像模块的div的ID
 * currentPic：初始显示头像路径
 * uploadUrl：接收上传头像的url
 * newPicPathBase：上传成功后新头像路径的前缀（加上文件名构成完整路径，其中文件名由接收上传头像的url异步返回）
 * newPicFileNameFormName：控件内部的input type=hidden控件的name的值（可选，默认值为pic）
 * imgBorder：图片周围的空白边框的大小（可选，默认为5）
 * onPicChanged：当图片变更时的回调函数（可选）
 */

function AvatarUpload(params){
	var id=params.id;
	var currentPic=params.currentPic;
	var uploadUrl=params.uploadUrl;
	var newPicPathBase=params.newPicPathBase;
	var newPicFileNameFormName=params.newPicFileNameFormName;
	var imgBorder=params.imgBorder;
	var onPicChanged=params.onPicChanged;
	
	var au = this;
	
	this.id=id;
	
	$(document).ready(function(){
		var width=$('#'+id).width();
		var height=$('#'+id).height();
		var border=Number(imgBorder?imgBorder:0);
		var innerWidth=width-border*2;
		var innerHeight=height-border*2;
		
		var addStyleClass = function(selector, rules, contxt) {
			var context = contxt || document, stylesheet;

			if (typeof context.styleSheets == 'object') {
				if (context.styleSheets.length) {
					stylesheet = context.styleSheets[context.styleSheets.length - 1];
				}
				if (context.styleSheets.length) {
					if (context.createStyleSheet) {
						stylesheet = context.createStyleSheet();
					} else {
						context.getElementsByTagName('head')[0]
								.appendChild(context.createElement('style'));
						stylesheet = context.styleSheets[context.styleSheets.length - 1];
					}
				}
				if (stylesheet.addRule) {
					for ( var i = 0; i < selector.length; ++i) {
						stylesheet.addRule(selector[i], rules);
					}
				} else {
					stylesheet.insertRule(selector.join(',') + '{' + rules
							+ '}', stylesheet.cssRules.length);
				}
			}
		};
		
		addStyleClass(['div.avatar_upload_'+id+' div.imgShowing img'],
				'width: '+innerWidth+'px; height: '+innerHeight+'px; margin-top: '
					+Math.max(border-1,0)+'px; margin-left: '
					+Math.max(border-1,0)+'px;'+(border!=0?' border: 1px solid #DEDEE6;':''));
		addStyleClass(['div.avatar_upload_'+id+' div.imgLoading'],
				'background: #fff url(../images/loading.gif) no-repeat '
					+parseInt((width-24)/2)+'px '+parseInt((height-24)/2)+'px;');
		addStyleClass(['div.avatar_upload_'+id+' div.imgLoading img'],
				'display: none;');
		
		var t=
			'																																		\
			<div class="avatar_upload_[id]" style="position: relative; left: 0; top: 0;">															\
			<div id="[id]AvatarImgContainer" class="imgShowing" 																					\
				style="position: absolute; left: 0; top: 0; width: [width]px; height: [height]px;">													\
				<img id="[id]AvatarImg" src="[currentPic]"/>																						\
			</div>																																	\
			<div id="[id]AvatarPrompt" 																												\
				style="position: absolute; left: 0; top: 0; width: [width]px; height: [height]px; display: none;">									\
				<div style="position: absolute; left: [border]px; top: [border]px; width: [innerWidth]px; height: [innerHeight]px; 					\
				background: black; filter: alpha(opacity=30); -moz-opacity: 0.3; opacity: 0.3;"></div>												\
				<div style="position: absolute; left: [border]px; top: [border]px; width: [innerWidth]px; height: [innerHeight]px; 					\
				color: black; text-align: center; font-size: 12px; line-height: [innerHeight]px;" class="aaaaaaaa">点击修改</div>										\
			</div>																																	\
			<div id="[id]AvatarTop"																													\
				style="position: absolute; left: 0; top: 0; width: [width]px; height: [height]px; overflow: hidden; cursor: hand;">					\
				<form id="[id]AvatarForm" action="[uploadUrl]">																						\
					<input type="file" id="[id]AvatarFile" 																							\
					style="width: [width]px; height: [height]px; line-height: [height]px; filter: alpha(opacity=0); -moz-opacity: 0; opacity: 0;" 	\
					size="1" contenteditable="false" title="点击修改"/>																				\
				</form>																																\
			</div>																																	\
			<input type="hidden" id="[id]AvatarNewPicFileName" name="[newPicFileName]" value=""/>													\
			</div>																																	\
			';			
			
		t=t.replace(/\[id\]/g,id);
		t=t.replace(/\[currentPic\]/g,currentPic);
		t=t.replace(/\[uploadUrl\]/g,uploadUrl);
		t=t.replace(/\[width\]/g,width);
		t=t.replace(/\[height\]/g,height);
		t=t.replace(/\[border\]/g,border);
		t=t.replace(/\[innerWidth\]/g,innerWidth);
		t=t.replace(/\[innerHeight\]/g,innerHeight);
		t=t.replace(/\[newPicFileName\]/g,newPicFileNameFormName?newPicFileNameFormName:'pic');
		
		$('#'+id).html(t);

		var onAvatarImgMouseOver=function(){
			if($('#'+id+'AvatarImgContainer').attr('class')=='imgLoading'){
				return;
			}
			var prom = $('#'+id+'AvatarPrompt');
			prom.show();
			prom.fadeOut(3000);
		};
		document.getElementById(id+'AvatarTop').onmouseover=onAvatarImgMouseOver;
		var thumb = $('#'+id+'AvatarImg');
		new AjaxUpload(id+'AvatarFile', {
			action : uploadUrl,
			name : 'image',
			allowedExtensions: ['jpg','jpeg','png','gif','bmp'],
			onSubmit : function(file, extension) {
				$('#'+id+'AvatarImgContainer').attr('class','imgLoading');
			},
			onComplete : function(file, response) {
				var err="error:";
				var fi="file:";
				if(response.substring(0,err.length)==err){
					CM.alert(response.substring(err.length));
					$('#'+id+'AvatarImgContainer').attr('class','imgShowing');
				}else if(response.substring(0,fi.length)==fi){
					var fileName=response.substring(fi.length);
					au.setPicPath(newPicPathBase+fileName);
					au.setFormValue(newPicPathBase+fileName);
					if(onPicChanged){
						onPicChanged(fileName);
					}
				}else{
					CM.alert("上传文件失败");
					$('#'+id+'AvatarImgContainer').attr('class','imgShowing');
				}
			}
		});
	});
}

AvatarUpload.prototype.setPicPath=function(picPath){
	var id=this.id;
	var thumb = $('#'+id+'AvatarImg');
	thumb.load(function() {
		$('#'+id+'AvatarImgContainer').attr('class','imgShowing');
	});
	thumb.attr('src', picPath);
};

AvatarUpload.prototype.setFormValue=function(value){
	var id=this.id;
	$('#'+id+'AvatarNewPicFileName').attr('value',value);
};
